package com.example.demo1.itlianxi08;

import com.example.demo1.itlianxi07.Student;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 构造真实类对象：反射对象.newInstance()
 * 执行方法：方法对象.invoke(对象，参数值)
 * 设置属性：属性对象.set(对象，属性值)
 * 属性可被修改：属性对象.setAccessible(true)
 */
public class ReflectDemo2 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {

        Class aClass = Class.forName("com.example.demo1.itlianxi07.Student");

        //通过Class 对象构造其真实类Student 的对象
        Student student = (Student)aClass.newInstance();

        Method setName = aClass.getDeclaredMethod("setName", String.class);
        setName.invoke(student,"zhangsan");
        System.out.println(student.getName());

        System.out.println("====================");

        Field age = aClass.getDeclaredField("age");
        age.setAccessible(true);
        age.set(student,18);
        System.out.println(student.getAge());
    }
}
